package com.tjmc.company.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.plugin.excel.annotation.RequestExcel;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import com.tjmc.company.api.entity.CompanyImgInfoEntity;
import com.tjmc.company.api.entity.CompanyInfoEntity;
import com.tjmc.company.api.entity.DeliveryRecordsEntity;
import com.tjmc.company.api.entity.JobInfoEntity;
import com.tjmc.company.api.enums.DeliveryRecordStatusEnum;
import com.tjmc.company.api.enums.JobStatusEnum;
import com.tjmc.company.service.CompanyImgInfoService;
import com.tjmc.company.service.CompanyInfoService;
import com.tjmc.company.service.DeliveryRecordsService;
import com.tjmc.company.service.JobInfoService;
import com.tjmc.recruit.admin.api.entity.PlatformUserInfoEntity;
import com.tjmc.recruit.admin.api.feign.RemoteUserService;
import com.tjmc.recruit.common.core.constant.SecurityConstants;
import com.tjmc.recruit.common.core.util.R;
import com.tjmc.recruit.common.log.annotation.SysLog;
import com.tjmc.recruit.common.security.annotation.Inner;
import com.tjmc.recruit.finance.api.feign.RemoteAccountService;
import com.tjmc.recruit.user.entity.PersonalReadRecordsEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 企业信息表
 *
 * @author recruit
 * @date 2024-11-13 14:47:16
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/companyInfo")
@Tag(description = "companyInfo", name = "企业信息表管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class CompanyInfoController {

    private final CompanyInfoService companyInfoService;
    private final JobInfoService jobInfoService;
    private final CompanyImgInfoService companyImgInfoService;
    private final DeliveryRecordsService deliveryRecordsService;
    private final RemoteAccountService remoteAccountService;
    private final RemoteUserService remoteUserService;

    /**
     * 分页查询
     *
     * @param page        分页对象
     * @param companyInfo 企业信息表
     * @return R
     */
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/page")
    @SysLog("分页查询")
    public R getCompanyInfoPage(@ParameterObject Page page, @ParameterObject CompanyInfoEntity companyInfo) {
        LambdaQueryWrapper<CompanyInfoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(companyInfo.getCompantSize()), CompanyInfoEntity::getCompantSize, companyInfo.getCompantSize());
        return R.ok(companyInfoService.selectPageOrdered(page, wrapper));
    }

    /**
     * 分页查询-开放接口
     *
     * @param page        分页对象
     * @param companyInfo 企业信息表
     * @return R
     */
    @Operation(summary = "分页查询-开放接口", description = "分页查询-开放接口")
    @GetMapping("/page/open")
    @SysLog("分页查询-开放接口")
    @Inner(value = false)
    public R getCompanyInfoPageOpen(@ParameterObject Page page, @ParameterObject CompanyInfoEntity companyInfo) {
        LambdaQueryWrapper<CompanyInfoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(companyInfo.getCompantSize()), CompanyInfoEntity::getCompantSize, companyInfo.getCompantSize());
        return R.ok(companyInfoService.selectPageOrdered(page, wrapper));
    }

    /**
     * 按类别查询企业
     *
     * @param page     分页信息
     * @param category 类别：MEMBER(会员)、HIGH_SAL(高薪)、FAM(名企)
     * @return
     */
    @Operation(summary = "按类别查询企业", description = "按类别查询企业")
    @GetMapping("/page/{category}")
    @SysLog("按类别查询企业")
    public R getCompanyInfoPageByCategory(@ParameterObject Page page, @PathVariable String category) {
        return R.ok(companyInfoService.getCompanyPageByCategory(page, category));
    }

    /**
     * 按类别查询企业-开放接口
     *
     * @param page     分页信息
     * @param category 类别：MEMBER(会员)、HIGH_SAL(高薪)、FAM(名企)
     * @return
     */
    @Operation(summary = "按类别查询企业-开放接口", description = "按类别查询企业-开放接口")
    @GetMapping("/page/open/{category}")
    @SysLog("按类别查询企业-开放接口")
    @Inner(value = false)
    public R getCompanyInfoPageByCategoryOpen(@ParameterObject Page page, @PathVariable String category) {
        return R.ok(companyInfoService.getCompanyPageByCategory(page, category));
    }

    /**
     * 根据ID查询企业详细信息
     *
     * @param id 企业ID
     * @return R 企业详细信息
     */
    @Operation(summary = "根据ID查询企业详细信息", description = "根据ID查询企业详细信息")
    @GetMapping("/{id}")
    public R getCompanyInfoById(@PathVariable Long id) {
        CompanyInfoEntity companyInfo = companyInfoService.getById(id);
        if (Objects.isNull(companyInfo)) {
            return R.failed("企业信息不存在");
        }
        //职位发布数据
        List<JobInfoEntity> list = jobInfoService.list(Wrappers.<JobInfoEntity>lambdaQuery()
                .eq(JobInfoEntity::getCompanyId, companyInfo.getId()).eq(JobInfoEntity::getStatus, JobStatusEnum.PUBLISHED));
        companyInfo.setJobList(list);
        companyInfo.setJobCount(list.size());
        List<CompanyImgInfoEntity> imgList = companyImgInfoService.list(Wrappers.<CompanyImgInfoEntity>lambdaQuery()
                .eq(CompanyImgInfoEntity::getCompanyId, companyInfo.getId()));
        companyInfo.setImgInfoList(imgList);
        //简历查看数据
        companyInfo.setResumeReadNum(deliveryRecordsService.count(Wrappers.<DeliveryRecordsEntity>lambdaQuery()
                .eq(DeliveryRecordsEntity::getCompanyId, companyInfo.getId())
                .eq(DeliveryRecordsEntity::getDeliveryStatus, DeliveryRecordStatusEnum.CHECK)));
        companyInfo.setResumeUnReadNum(deliveryRecordsService.count(Wrappers.<DeliveryRecordsEntity>lambdaQuery()
                .eq(DeliveryRecordsEntity::getCompanyId, companyInfo.getId())
                .eq(DeliveryRecordsEntity::getDeliveryStatus, DeliveryRecordStatusEnum.UNCHECK)));
        //被浏览数据
        companyInfo.setBrowsedNum(companyInfoService.countBeBrowsedNum(companyInfo));
        return R.ok(companyInfo);
    }

    /**
     * 新增企业信息表
     *
     * @param companyInfo 企业信息表
     * @return R
     */
    @Operation(summary = "新增企业信息表", description = "新增企业信息表")
    @SysLog("新增企业信息表")
    @PostMapping
    public R save(@RequestBody CompanyInfoEntity companyInfo) {
        //如果fullName存在则不允许新增
        CompanyInfoEntity one = companyInfoService.getOne(new LambdaQueryWrapper<CompanyInfoEntity>().eq(CompanyInfoEntity::getFullName, companyInfo.getFullName()));
        if (one != null) {
            return R.failed("企业已存在");
        }
        return R.ok(companyInfoService.save(companyInfo));
    }

    /**
     * 修改企业信息表
     *
     * @param companyInfo 企业信息表
     * @return R
     */
    @Operation(summary = "修改企业信息表", description = "修改企业信息表")
    @SysLog("修改企业信息表")
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public R updateById(@RequestBody CompanyInfoEntity companyInfo) {
        List<CompanyImgInfoEntity> imgInfoList = companyInfo.getImgInfoList();
        if (imgInfoList != null && !imgInfoList.isEmpty()) {
            Set<Long> set = imgInfoList.stream().map(CompanyImgInfoEntity::getCompanyId).collect(Collectors.toSet());
            companyImgInfoService.remove(new LambdaQueryWrapper<>(CompanyImgInfoEntity.class).in(CompanyImgInfoEntity::getCompanyId, set));
            companyImgInfoService.saveBatch(imgInfoList);
        }
        return R.ok(companyInfoService.updateById(companyInfo));
    }

    /**
     * 通过id删除企业信息表
     *
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除企业信息表", description = "通过id删除企业信息表")
    @SysLog("通过id删除企业信息表")
    @DeleteMapping
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(companyInfoService.removeBatchByIds(CollUtil.toList(ids)));
    }

    /**
     * 注册用户时-新增企业
     *
     * @param companyInfo 企业信息
     * @return R
     */
    @Inner
    @PostMapping("/add")
    public R add(@RequestBody CompanyInfoEntity companyInfo) {
        return companyInfoService.registerCompany(companyInfo);
    }
}
